package com.ksana.orm.session.impl;

import com.ksana.orm.config.Configuration;
import com.ksana.orm.executor.Executor;
import com.ksana.orm.executor.impl.DefaultExecutor;
import com.ksana.orm.proxy.MapperProxy;
import com.ksana.orm.session.SqlSession;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.SQLException;
import java.util.List;

public class DefaultSqlSession implements SqlSession {
    private Executor executor = new DefaultExecutor();

    @Override
    public <T> T selectOne(Method statement, Object... parameters) throws Exception {
        return executor.selectOne(statement, parameters);
    }

    @Override
    public <T> List<T> selectList(Method statement, Object... parameters) throws Exception {
        return executor.selectList(statement, parameters);
    }

    @Override
    public Integer insert(Method statement, Object... parameters) throws Exception {
        return executor.insert(statement, parameters);
    }

    @Override
    public Integer update(Method statement, Object... parameters) throws Exception {
        return executor.update(statement, parameters);
    }

    @Override
    public Integer delete(Method statement, Object... parameters) throws Exception {
        return executor.delete(statement, parameters);
    }

    @Override
    public <T> T getMapper(Class<T> cla) {
        // 动态代理 对接口经行注册如果使用接口中的方法 则会调用 InvocationHandler 中被实现的 invoke 方法
        return (T) Proxy.newProxyInstance(cla.getClassLoader(), new Class[] {cla}, new MapperProxy(this));
    }

    @Override
    public void commit() throws Exception {
        try {
            new Configuration().build().commit();
        } catch (SQLException e) {
            throw new Exception("提交失败");
        }
    }

    @Override
    public void rollback() throws Exception {
        try {
            new Configuration().build().rollback();
        } catch (SQLException e) {
            throw new Exception("回滚失败");
        }
    }
}
